$(function () {
  // 判断设备类型
  try {
    var equipment = eval(getComputedStyle(document.documentElement).getPropertyValue('--equipment'));
  } catch (error) {
    console.log(error);
  }

  // 获取cookie
  function getCookie (objName) {
    var arrStr = document.cookie.split("; ");
    for (var i = 0; i < arrStr.length; i++) {
      var temp = arrStr[i].split("=");
      if (temp[0] == objName && objName == "UD") return decodeURIComponent(temp[1]);
      if (temp[0] == objName) return decodeURI(temp[1]);
    }
  }

  // 设置cookie
  function setCookie (name, value, t) {
    var exp = new Date();
    if (t == -1) {
      document.cookie = name + "=" + escape(value) + ";domain=.csdn.net;path=/";
      return
    }
    if (!t) {
      var Days = 30;
      exp.setTime(exp.getTime() + Days * 24 * 60 * 60 * 1000);

    } else {
      exp.setTime(exp.getTime() + t);
    }
    document.cookie = name + "=" + escape(value) + ";expires=" + exp.toGMTString() + ";domain=.csdn.net;path=/";
  }

  // 获取url中的参数方法
  function getUrlParam (name) {
    var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
    var r = window.location.search.substr(1).match(reg);
    if (r != null) {
      return unescape(r[2]);
    } else {
      return null;
    }
  }

  var username = getUrlParam('username'); // 从url拿到参数
  var page = 1; // 排行榜分页
  var id = ''; // 投票的id
  var ENV = 'prod';
  var API_URL = '';

  if (ENV === 'test') {
    API_URL = 'https://betabss.csdn.net/m/topic/blog_star2020';
    // API_URL = 'http://lbss.csdn.net/m/topic/blog_star2020';
  } else if (ENV === 'prod') {
    API_URL = 'https://bss.csdn.net/m/topic/blog_star2020';
  }

  // 模态框尺寸 二维码尺寸
  var modalWidth = null;
  var qrcodeWidth = null;
  if (equipment === 'pc') {
    modalWidth = '350px';
    qrcodeWidth = 99;
  } else {
    modalWidth = '250px';
    qrcodeWidth = 71;
  }
  var knowRuleData = {}; // 投票规则数据
  var voteForFlag = true;
  var canvassingFlag = true;
  var timer;
  var getRankingListFlag = true; // 获取排行榜列表数据

  // 埋点数据
  var canvassingMod = '';
  var canvassingSpm = '';
  var bloggerMod = '';
  var bloggerSpm = '';
  if (equipment === 'pc') {
    canvassingMod = '1610099395_002';
    canvassingSpm = '1014.2231.3001.5457';
    bloggerMod = '1610099395_004';
    bloggerSpm = '1014.2231.3001.5459';
  } else {
    canvassingMod = '1610099395_003';
    canvassingSpm = '1014.2231.3001.5458';
    bloggerMod = '1610099395_005';
    bloggerSpm = '1014.2231.3001.5460';
  }

  // 埋点 曝光
  csdn && csdn.report && csdn.report.reportView && csdn.report.reportView({
    mod: canvassingMod
  });
  csdn && csdn.report && csdn.report.reportView && csdn.report.reportView({
    mod: bloggerMod
  });
  // 模态框
  var modal = {
    voteSuccessful: voteSuccessful,
    voteSuccessful2: voteSuccessful2,
    voteFailed: voteFailed,
    voteFailed2: voteFailed2,
    voteNumIncrease: voteNumIncrease,
    knowRule: knowRule,
    bindPhoneNum: bindPhoneNum,
    noBlog: noBlog,
    loginRequired: loginRequired,
    scanQrcode: scanQrcode,
    share: share,
    userNotExist: userNotExist
  }

  // 节流
  function throttle (func, delay) {
    var prev = Date.now();
    return function () {
      var context = this;
      var args = arguments;
      var now = Date.now();
      if (now - prev >= delay) {
        func.apply(context, args);
        prev = Date.now();
      }
    }
  }

  // 获取投票数据
  function getBloggerInfo (callback) {
    $.ajax({
      type: 'get',
      url: `${API_URL}/getUserDetail`,
      data: {
        username: username
      },
      dataType: 'json',
      success: function (res) {
        if (res.code === 200) {
          var bloggerInfo = $('#bloggerInfo');
          var data = res.data;
          id = data.id;
          bloggerInfo.find('.avatar img').attr('src', data.avatar);
          bloggerInfo.find('.serial').text(data.number);
          bloggerInfo.find('.name').text(data.nick_name);
          bloggerInfo.find('.level span').text(data.codeLevel);
          bloggerInfo.find('.level .icon-level').addClass('icon-level-' + data.level);
          bloggerInfo.find('.statistics span').text(data.article_count);
          bloggerInfo.find('.current-vote strong').text(data.vote_num);
          bloggerInfo.find('.link').attr('href', `https://blog.csdn.net/${data.title}`);
          if (typeof callback === 'function') {
            callback();
          }
        }else {
          // 是否登录
          if (!isLogin()) {
            modal.loginRequired();
            return;
          }
          modal.userNotExist(res.msg);
        }
      },
      error: function (err) {
        console.log(err);
      }
    });
  }

  // 获取排行榜列表
  function getRankingList (currentPage, callback) {
    if (!getRankingListFlag) return;
    getRankingListFlag = false;
    $.ajax({
      type: 'post',
      url: `${API_URL}/getRanking`,
      data: {
        username: username,
        page: currentPage,
        pageSize: 20
      },
      dataType: 'json',
      success: function (res) {
        var data = res.data.length !== 0 ? res.data : '[]';
        data = JSON.parse(data);
        var html = '';
        var maxVote = null;
        $.each(data, function (index, item) {
          var num = (currentPage - 1) * 20 + index + 1;
          if (num === 1) {
            maxVote = item.voteNum;
          }
          var bestBlogger = item.voteNum === maxVote ? '<span class="best-blogger"></span>' : '';
          var isBestBlogger = item.voteNum === maxVote ? 'best-blogger-wrapper' : '';
          html += `
            <li class="${isBestBlogger}">
              <div class="left">
                <span class="num">${item.number}</span>
                <span class="text">${item.nick_name}</span>
                <span class="icon-level icon-level-${item.level}"></span>
                ${bestBlogger}
              </div>
              <div class="right">
                <span class="code-age">码龄${item.codeLevel}年</span>
                <span class="vote-num">${item.voteNum}票</span>
              </div>
            </li>
          `;
        });
        if (currentPage === 1 && data.length === 0) {
          $('#voteLeaderboardList').addClass('no-data-wrapper');
          html = `
            <div class="no-data">
              <i class="icon-no-data"></i>
              暂无数据～
            </div>
          `;
        }
        // 超过一页时追加
        if (currentPage === 1) {
          $('#voteLeaderboardList').html(html);
        } else {
          $('#voteLeaderboardList').append(html);
        }
        if (typeof callback === 'function') {
          callback(data);
        }
      },
      error: function (err) {
        console.log(err);
        --page;
      },
      complete: function () {
        getRankingListFlag = true;
      }
    });
  }

  // 获取登录用户票数信息
  function getUserVoteNum () {
    // 是否登录
    if (!isLogin()) {
      modal.loginRequired();
      return;
    }
    // 关键性校验
    window.csdn.userLogin.loadAjax(function (res) {
      if (!res.status) {
        modal.bindPhoneNum(res.error);
      } else {
        $.ajax({
          type: 'post',
          url: `${API_URL}/getUserVoteNum`,
          data: {
            loginUsername: getCookie('UserName')
          },
          dataType: 'json',
          success: function (res) {
            try {
              var data = res.data;
              data = JSON.parse(data);
              knowRuleData = data;
              // 数据照常展示
              var isExpert = data.blog.is_expert ? '尊贵的博客专家，' : '';
              $('#voteNum').html(`${isExpert}您今天可投 <span>${data.userNum}</span> 票`);

              if (data.userNum === 0) {
                $('#voteFor').addClass('disabled');
              }

              data = $.extend({}, { UserName: getCookie('UserName') }, data); // 把当前用户名也存到cookie里
              if (res.code === 200) {
                saveBlogStarData(data);
              } else if (res.code === 400003) { // 无权投票 未发布博文
                modal.noBlog();
              }
            } catch (error) {
              console.log(error);
            }
          },
          error: function (err) {
            console.log(err);
          }
        });
      }
    });
  }

  // 第一次进入页面 cookie里没有 把数据存到cookie里 blogStar
  // 同一个用户不一致才提示 要判断UserName是否一致
  function saveBlogStarData (data) {
    var UserName = getCookie('UserName');
    if (getCookie('blogStar') === undefined) {
      setCookie('blogStar', encodeURIComponent(JSON.stringify(data)));
      modal.knowRule(data);
    } else { // cookie里有 对比一下是否有变化
      var blogStar = JSON.parse(decodeURIComponent(getCookie('blogStar')));      
      // 首先判断是否是同一个人
      if (blogStar.UserName === UserName) {
        var msgArr = [];
        var msg = '';
        if (blogStar.blog.num !== data.blog.num || blogStar.codeYear.num !== data.codeYear.num || blogStar.blog.is_expert !== data.blog.is_expert) {
          if (blogStar.blog.num !== data.blog.num) {
            msgArr.push('等级提升');
          }
          if (blogStar.codeYear.num !== data.codeYear.num) {
            msgArr.push('码龄增加');
          }
          if (blogStar.blog.is_expert !== data.blog.is_expert) {
            msgArr.push('申请为博客专家');
          }

          if (msgArr.length > 1) {
            $.each(msgArr, function (index, item) {
              msg += item;
              if (index !== msgArr.length - 1) {
                msg += '、';
              }
            });
          } else {
            msg = msgArr[0];
          }
          modal.voteNumIncrease(data, msg);
          setCookie('blogStar', encodeURIComponent(JSON.stringify(data)));
        }
      } else {
        modal.knowRule(data);
        setCookie('blogStar', encodeURIComponent(JSON.stringify(data)));
      }
    }
  }

  // 判断是否登录
  function isLogin () {
    var UserName = getCookie('UserName');
    return UserName !== undefined;
  }

  // 页面初始化
  function init (page) {
    getBloggerInfo(getUserVoteNum);
    getRankingList(page);
    // getUserVoteNum();
  }

  init(page);

  // 绑定事件
  // 页面滚动 高亮 吸顶
  $('#voteLeaderboardList').scroll(throttle(function () {
    var scrollTop = $(this).scrollTop();
    var voteLeaderboardListIh = $('#voteLeaderboardList').innerHeight();
    var voteLeaderboardListSh = $('#voteLeaderboardList')[0].scrollHeight;
    if (scrollTop >= voteLeaderboardListSh - voteLeaderboardListIh && getRankingListFlag) {
      // $('#voteLeaderboardList .load-more').show(); // TODO 显示loading
      // 如果没有更多数据的话 页码还原回去
      getRankingList(++page, function (data) {
        if (data.length === 0) {
          --page;
        }
      });
    }
  }, 10));

  // 票数+1
  $('#counter .add').on('click', function () {
    if (!isLogin()) {
      modal.loginRequired();
      return;
    }
    var num = parseInt($('#counter .num').text());
    var max = parseInt($('#voteNum span').text());
    if (++num <= max) {
      $('#counter .num').text(num);
    }
  });

  // 票数-1
  $('#counter .sub').on('click', function () {
    if (!isLogin()) {
      modal.loginRequired();
      return;
    }
    var num = parseInt($('#counter .num').text());
    if (--num >= 1) {
      $('#counter .num').text(num);
    }
  });

  // 最大票数
  $('#maximum').on('click', function () {
    if (!isLogin()) {
      modal.loginRequired();
      return;
    }
    var max = parseInt($('#voteNum span').text());
    if (max < 1) {
      max = 1;
    }
    if (isNaN(max)) {
      max = 1;
    }
    $('#counter .num').text(max);
  });

  // 投TA一票
  $('#voteFor').on('click', function () {
    if (!isLogin()) {
      modal.loginRequired();
      return;
    }
    window.csdn.userLogin.loadAjax(function (res) {
      if (!res.status) {
        modal.bindPhoneNum(res.error);
      } else {
        if ($('#voteFor').hasClass('disabled')) return;
        if (!voteForFlag) return;
        voteForFlag = false;
        $.ajax({
          type: 'post',
          url: `${API_URL}/userVote`,
          data: {
            username: username,
            voteNum: parseInt($('#counter .num').text()),
            id: id,
            loginUsername: getCookie('UserName')
          },
          dataType: 'json',
          success: function (res) {
            if (res.code === 200) {
              if (res.data.voteNum === 0) {
                modal.voteSuccessful2(res.data.voteNum);
              } else {
                modal.voteSuccessful(res.data.voteNum);
              }
              init(page = 1);
            } else if (res.code === 400006) {
              modal.voteFailed2(res.msg);
            } else if (res.code === 400003) {
              modal.voteFailed2('您还未发布过博文，无投票权！快去发博吧~');
            } else {
              modal.voteFailed2(res.msg);
            }
          },
          error: function (err) {
            console.log(err);
          },
          complete: function () {
            voteForFlag = true;
          }
        });
      }
    });
  });

  $('#canvassing').on('click', function (e) {
    // 埋点 点击
    csdn && csdn.report && csdn.report.reportClick && csdn.report.reportClick({
      mod: canvassingMod,
      spm: canvassingSpm
    });
    if (equipment === 'pc') {
      modal.scanQrcode();
    } else {
      if (!canvassingFlag) return;
      canvassingFlag = false;
      modal.share(function (mModal1) {
        timer = setTimeout(function () {
          mModal1.close();
          canvassingFlag = true;
        }, 2000);
      });
    }
  });

  // 关闭模态框
  $(document).on('click', '.share .m-modal__headerbtn', function () {
    clearTimeout(timer);
    canvassingFlag = true;
  });

  // 查看可投票数
  $('#voteNum').on('click', function () {
    modal.knowRule(knowRuleData);
  });

  // 点击博主信息埋点
  $('.blogger .link').on('click', function () {
    // 埋点 点击
    csdn && csdn.report && csdn.report.reportClick && csdn.report.reportClick({
      mod: bloggerMod,
      spm: bloggerSpm
    });
  });
  // 模态框
  // 投票成功
  function voteSuccessful (voteNum) {
    var mModal1 = new mModal({
      title: '',
      customClass: 'vote-successful',
      content: `<p>投票成功！</p><p>您今天还可投 <strong>${voteNum}</strong> 票</p><p>过期可是作废的哦~</p>`,
      cancelText: '继续投票',
      confirmText: '给其他博主投票',
      width: modalWidth,
      top: '30vh',
      cancel: function () {},
      confirm: function () {
        window.open('./index', '_blank');
      }
    });
    mModal1.renderDom();
  }

  // 投票成功 剩余0票时 文案不一样
  function voteSuccessful2 (voteNum) {
    var mModal1 = new mModal({
      title: '',
      customClass: 'vote-successful',
      content: `<p>投票成功！</p><p>您今天还可投 <strong>${voteNum}</strong> 票</p>`,
      width: modalWidth,
      top: '30vh',
      showCancelButton: false,
      showConfirmButton: false
    });
    mModal1.renderDom();
  }


  // 投票失败
  function voteFailed (msg) {
    var mModal1 = new mModal({
      title: '',
      customClass: 'vote-failed',
      content: `<p>投票失败！</p><p>${msg}</p>`,
      confirmText: '给其他博主投票',
      width: modalWidth,
      top: '30vh',
      showCancelButton: false,
      confirm: function () {
        window.open('./index', '_blank');
      }
    });
    mModal1.renderDom();
  }
// 投票失败2 隐藏按钮
  function voteFailed2 (msg) {
    var mModal1 = new mModal({
      title: '',
      customClass: 'vote-failed2',
      content: `<p>投票失败！</p><p>${msg}</p>`,
      width: modalWidth,
      top: '30vh',
      showCancelButton: false,
      showConfirmButton: false
    });
    mModal1.renderDom();
  }
  // 投票次数增加
  function voteNumIncrease (data, msg) {
    var mModal1 = new mModal({
      title: '',
      customClass: 'vote-num-increase',
      content: `<p>恭喜！由于您${msg}，因此每天的投票次数增加到 <strong>${data.userTotalNum}</strong> 次了！</p>`,
      cancelText: '了解',
      width: modalWidth,
      top: '30vh',
      cancel: function () {},
      showConfirmButton: false
    });
    mModal1.renderDom();
  }

  // 了解投票规则
  function knowRule (data) {
    var blogExpert = data.blog.is_expert ? `<p class="blog-expert"><span>博客专家</span><span>+<i>${data.blog.expert_num}</i>票</span></p>` : '';
    var mModal1 = new mModal({
      title: '',
      customClass: 'know-rule',
      content: `<div class="intro"><p>尊贵的 <strong>${data.nick_name}</strong> 您好，根据《博客之星》投票权重规则，活动期间您每天将拥有  <strong>${data.userTotalNum}</strong> 投票机会。如下：</div><div class="vote-num"><p class="blog"><span class="level">博客等级<i>${data.blog.level}</i></span><span class="vote">+<i>${data.blog.num}</i>票</span></p><p class="level"><span class="code-year">码龄<i>${data.codeYear.year}</i></span><span class="vote">+<i>${data.codeYear.num}</i>票</span></p>${blogExpert}</div>`,
      confirmText: '了解',
      width: modalWidth,
      top: '30vh',
      cancelText: '了解',
      showCancelButton: false,
      confirm: function () {
        mModal1.close();
      }
    });
    mModal1.renderDom();
  }

  // 绑定手机号
  function bindPhoneNum (error) {
    var mModal1 = new mModal({
      title: '',
      customClass: 'bind-phone-num',
      content: `<p>${error || '您需绑定手机号才能投票哦'}~</p>`,
      width: modalWidth,
      top: '30vh',
      cancelText: '取消',
      confirmText: '去绑定',
      cancel: function () {},
      confirm: function () {
        window.open('https://i.csdn.net/#/account/index');
      }
    });
    mModal1.renderDom();
  }

  // 未发布过博文
  function noBlog () {
    var mModal1 = new mModal({
      title: '',
      customClass: 'no-blog',
      content: '<p>您还未发布过博文，无投票权！快去发博吧~</p>',
      width: modalWidth,
      top: '30vh',
      cancelText: '取消',
      confirmText: '去发博',
      showCancelButton: false,
      confirm: function () {
        window.open('https://mp.csdn.net/console/home');
      }
    });
    mModal1.renderDom();
  }

  // 您需登录才能投票
  function loginRequired () {
    var mModal1 = new mModal({
      title: '',
      customClass: 'login-required',
      content: '<p>您需登录才能投票</p>',
      width: modalWidth,
      top: '30vh',
      confirmText: '立即登录',
      showCancelButton: false,
      confirm: function () {
        if (equipment === 'pc') {
          csdn.loginBox.show();
        } else {
          var href = 'https://passport.csdn.net/account/login?from=' + encodeURIComponent(location.href);
          window.open(href);
        }
      }
    });
    mModal1.renderDom();
  }

  // pc 为他拉票 扫描二维码
  function scanQrcode () {
    var mModal1 = new mModal({
      title: '',
      customClass: 'scan-qrcode',
      content: '<div class="qrcode-wrapper"><div id="qrcode" class="qrcode"></div><div class="text"><p>扫描二维码</p><p>为他拉票</p></div>',
      width: modalWidth,
      top: '30vh',
      showCancelButton: false,
      showConfirmButton: false
    });
    mModal1.renderDom();
    $('#qrcode').qrcode({
      width: qrcodeWidth,
      height: qrcodeWidth,
      text: location.href
    });
  }

  // wap 为他拉票 提示
  function share (callback) {
    var mModal1 = new mModal({
      title: '',
      customClass: 'share',
      content: '<p>快去分享为TA拉票吧！</p>',
      width: modalWidth,
      top: '30vh',
      showCancelButton: false,
      showConfirmButton: false
    });
    mModal1.renderDom();
    if (typeof callback === 'function') {
      callback(mModal1);
    }
  }
  // 用户不存在
  function userNotExist (msg) {
    var mModal1 = new mModal({
      title: '',
      customClass: 'user-not-exist',
      content: `<p>${msg}</p>`,
      confirmText: '给其他博主投票',
      width: modalWidth,
      top: '30vh',
      showCancelButton: false,
      confirm: function () {
        window.open('./index', '_blank');
      }
    });
    mModal1.renderDom();
  }
});